<?php
include_once "model/exception/UserException.php";
include_once "model/User.php";
include_once "dao/DBConnector.php";

class UserDAO{

	public static function get_user($email, $password){
		$sql = "SELECT email, name, password, user_id FROM USER WHERE email = ? AND password = ? AND (deleted IS NULL OR deleted = FALSE)";
		$connection = DBConnector::get_connection();
		$stmt = $connection->prepare($sql);
		$clean_email = $connection->real_escape_string($email);
		$clean_password = $connection->real_escape_string($password);
		$stmt->bind_param('ss', $clean_email, $clean_password);
		$stmt->execute();
		$stmt->bind_result($u_email, $u_name, $u_password, $u_id);
		
		$user;
		if($stmt->fetch()){
			$user = new User($u_email, $u_name, $u_password, $u_id);
			$stmt->close();
			DBConnector::close($connection);
		} else {
			$stmt->close();
			DBConnector::close($connection);
			throw new UserException("User doesn't exists");
		}

		return $user;
	}

	public static function store($user){
		$new_user;

		if($user->get_user_id() == null){
			$new_user = UserDAO::add($user);
		} else {
			$new_user = UserDAO::update($user);
		}
		return $new_user;
	}


	private static function add($user){	
		$sql = "INSERT INTO USER (name, password, email, modification_date, creation_date) values( ?, ?, ?, current_timestamp, current_timestamp)";

		$name = $user->get_name();
		$password = $user->get_password();
		$email = $user->get_email();
		
		$connection = DBConnector::get_connection();
		$stmt = $connection->prepare($sql);
		$stmt->bind_param('sss', $name, $password, $email);
		$stmt->execute();
		$id = $connection->insert_id;
		$stmt->close();
		DBConnector::close($connection);
		
		return new User($email, $name, $password, $id);
	}

	
	private static function update($user){
		$sql = "UPDATE USER SET name = ?, password = ?, email = ? modification_date = current_timestamp  WHERE user_id = ?";
		$connection = DBConnector::get_connection();
		$stmt = $connection->prepare($sql);
		
		$name = $user->get_name();
		$id = $user->get_id();
		$password = $user->get_passowrd();
		$email = $user->get_email();

		$stmt->bind_param('sssi', $name, $password, $email, $id);
		$stmt->execute();
		$stmt->close();
		DBConnector::close($connection);

		return $user;
	}


	public static function remove($id){
		$sql = "UPDATE USER SET deleted = TRUE WHERE user_id = ".$id;
		$connection = DBConnector::get_connection();
		$connection->query($sql);
		DBConnector::close($connection);
	}

}

?>
